package com.ccp.dev.extend.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.ExceptionUtil;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringPool;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.model.FormDef;
import com.ccp.dev.form.model.PrintTemplate;
import com.ccp.dev.form.service.FormDefService;
import com.ccp.dev.form.service.PrintTemplateService;
import com.ccp.dev.system.model.GlobalType;
import com.ccp.dev.system.model.SysProperty;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.system.model.UserPosition;
import com.ccp.dev.system.service.SysUserService;
import com.ccp.dev.system.service.UserPositionService;
import com.ccp.dev.workflow.bpmutil.ServiceUtil;
import com.ccp.dev.workflow.model.*;
import com.ccp.dev.workflow.model.bpm.ProcessTask;
import com.ccp.dev.workflow.model.bpm.TaskExecutor;
import com.ccp.dev.workflow.model.bpm.TaskVars;
import com.ccp.dev.workflow.service.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * ClassDescribe: 流程控制器
 *
 * @author :wangcheng
 * Date: 2019-04-16
 * Since:1
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + "/extend/processRun")
@Action(ownermodel = SysAuditModelType.PROCESS_MANAGEMENT)
public class ExtendProcessRunController extends SysBaseController {
    private static final Logger logger = LoggerFactory.getLogger(ProcessRunService.class);

    @Resource
    private ProcessRunService processRunService;
    @Resource
    private ActDefModelService actDefModelService;
    @Resource
    private TaskOpinionService taskOpinionService;
    @Resource
    private FormDefService bpmFormDefService;
    @Resource
    private BpmDefAuthorizeService bpmDefAuthorizeService;
    @Resource
    private BpmService bpmService;
    @Resource
    private TaskVarsService taskVarsService;
    @Resource
    private PrintTemplateService bpmPrintTemplateService;
    @Resource
    private SysTemplateService sysTemplateService;
    @Resource
    private TaskService taskService;
    @Resource
    private TaskMessageService taskMessageService;
    @Resource
    private UserPositionService userPositionService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private TaskReadService taskReadService;
    @Resource
    private TaskUserService taskUserService;
    @Resource
    private FormHandlerService formHandlerService;


    /**
     * 根据分管授权情况查询流程实例数据
     * @param request request
     * @return Object
     */
    @RequestMapping("/processInstance")
    @Action(description = "根据分管授权情况查询流程实例数据",detail = "根据分管授权情况查询流程实例数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public Object list(HttpServletRequest request) {
        try {
            QueryFilter filter = new QueryFilter(request, true);
            // 过滤掉草稿实例
            filter.addFilter("exceptStatus", 4);
            // 过滤流程定义状态为"禁用实例" 的流程实例
            filter.addFilter("exceptDefStatus", 3);
            // 增加按新的流程分管授权中任务类型的权限获取流程的任务
            String userId = ContextUtil.getCurrentUserId();
            String isNeedRight = "";
            Map<String, AuthorizeRight> authorizeRightMap = null;
            if (!ContextUtil.isSuperAdmin()) {
                isNeedRight = "yes";
                //获得流程分管授权与用户相关的信息
                Map<String, Object> actRightMap = bpmDefAuthorizeService.getActRightsByUserMap(userId, BpmDefAuthorizeType.BPMDEFAUTHORIZE_RIGHT_TYPE.INSTANCE, true, false);
                //获得流程分管授权与用户相关的信息集合的流程KEY
                String actRights = (String) actRightMap.get("authorizeIds");
                filter.addFilter("actRights", actRights);
                //获得流程分管授权与用户相关的信息集合的流程权限内容
                authorizeRightMap = (Map<String, AuthorizeRight>) actRightMap.get("authorizeRightMap");
            }
            filter.addFilter("isNeedRight", isNeedRight);
            List<ProcessRun> list = processRunService.getAll(filter);

            // 把前面获得的流程分管授权的权限内容设置到流程管理列表
            if (authorizeRightMap != null) {
                for (ProcessRun processRun : list) {
                    processRun.setAuthorizeRight(authorizeRightMap.get(processRun.getFlowKey()));
                }
            } else {
                // 如果需要所有权限的就直接虚拟一个有处理权限的对象
                AuthorizeRight authorizeRight = new AuthorizeRight();
                authorizeRight.setRightByAuthorizeType("Y", BpmDefAuthorizeType.BPMDEFAUTHORIZE_RIGHT_TYPE.INSTANCE);
                for (ProcessRun processRun : list) {
                    processRun.setAuthorizeRight(authorizeRight);
                }
            }
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            ResultData resultDataSuccess = getResultDataSuccess("query.success", filter.getPageBean().getTotalCount(), list);
            return JSONObject.fromObject(resultDataSuccess).toString();
        } catch (Exception e) {
            logger.error(e.getMessage());
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 查看流程实例管理页面
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/processInstance")
    @Action(description = "查看流程实例管理页面", detail = "查看流程实例管理页面")
    public String viewRunningProcessInstanceList(Model model) {
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        model.addAttribute("privacyLevel", sysUser.getPrivacyLevel());
        return getAutoView();
    }

    /**
     * 删除流程实例
     * @param request request
     * @return ResultData
     */
    @RequestMapping(value = "del", method = RequestMethod.DELETE)
    @Action(description = "删除流程实例",detail = "删除流程实例，实例id包含${runId}，操作<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData del(HttpServletRequest request) {
        try {
            String[] lAryId = RequestUtil.getStringAryByStr(request, "runId");
            processRunService.delByIds(lAryId);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("delete.success");
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("delete.failure");
        }
    }

    /**
     * 查询流程实例历史数据
     * @param request request
     * @return Object
     */
    @RequestMapping("/history")
    @Action(description = "查询流程实例历史数据",detail = "查询流程实例历史数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public Object history(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        SysUser curUser = (SysUser) ContextUtil.getCurrentUser();
        String tenId = curUser.getTenantId();
        if (tenId != null) {
            queryFilter.addFilter("tenantId", tenId);
        }
        try {
            List<ProcessRun> list = processRunService.queryAllHistory(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            ResultData resultDataSuccess = getResultDataSuccess("query.success", queryFilter.getPageBean().getTotalCount(), list);
            return JSONObject.fromObject(resultDataSuccess).toString();
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("query.failure",1,e.getMessage());
        }

    }

    /**
     * 查看流程历史管理页面
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/history")
    @Action(description = "查看流程历史管理页面",detail = "查看流程历史管理页面")
    public String viewRunningProcessHistoryList(Model model) {
        SysUser user = (SysUser) ContextUtil.getCurrentUser();
        model.addAttribute("privacyLevel", user.getPrivacyLevel());
        return getAutoView();
    }

    /**
     * 获取办结事宜、已办事宜流程分类
     * @return ResultData
     */
    @RequestMapping("/getAlreadyMatterAndCompletedMattersType")
    @ResponseBody
    public ResultData getAlreadyMatterAndCompletedMattersType(HttpServletRequest request){
        String category = RequestUtil.getString(request,"category");
        String assignee =  ContextUtil.getCurrentUserId();
        List<GlobalType> processRunList = processRunService.queryAlreadyMatterAndCompletedMattersTypeList(assignee,category);
        return getResultDataSuccess("query.success",processRunList);
    }

    /**
     * 已办事宜列表
     *
     * @param request http协议
     * @return 返回已办事宜结果集
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST + "/alreadyMatter")
    @Action(ownermodel=SysAuditModelType.PROCESS_CENTER,description ="查询已办事宜列表数据",detail = "查询已办事宜列表数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public Object alreadyMattersList(HttpServletRequest request) {
        //构造QueryFilter，默认为分页处理。
        QueryFilter queryFilter = new QueryFilter(request);

        String nodePath = RequestUtil.getString(request, "nodePath");
        if (StringUtil.isNotEmpty(nodePath)) {
            queryFilter.addFilter("nodePath", nodePath + "%");
        }

        queryFilter.addFilter("assignee", ContextUtil.getCurrentUserId());
        try {
            List<ProcessRun> processRunList = processRunService.queryAlreadyMatterList(queryFilter);
            for (ProcessRun processRun : processRunList) {
                if (processRun.getStatus().shortValue() != ProcessRun.STATUS_FINISH.shortValue()) {
                    // 1.查找当前用户是否有最新审批的任务
                    TaskOpinion taskOpinion = taskOpinionService.getLatestUserOpinion(processRun.getProcInstId(), ContextUtil.getCurrentUserId());
                    if (BeanUtils.isNotEmpty(taskOpinion)) {
                        processRun.setRecover(ProcessRun.STATUS_RECOVER);
                    }
                }
            }
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("query.success", queryFilter.getPageBean().getTotalCount(), processRunList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 已办事宜页面跳转
     * @return 跳转路径
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/alreadyMatter")
    @Action(ownermodel=SysAuditModelType.PROCESS_CENTER,description ="查看已办事宜页面")
    public String viewAlreadyMatter() {
        return getAutoView();
    }

    /**
     * 办结事宜页面跳转
     *
     * @return 跳转路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/completedMatters")
    @Action(ownermodel=SysAuditModelType.PROCESS_CENTER,description ="查看办结事宜页面")
    public String viewCompletedMatters() {
        return getAutoView();
    }

    /**
     * 查看办结事宜流程列表
     * @param request request
     * @return Object
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST + "/completedMatters")
    @Action(ownermodel=SysAuditModelType.PROCESS_CENTER,description ="查询办结事宜列表数据",detail = "查询办结事宜列表数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public Object completedMattersList(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request);
        String nodePath = RequestUtil.getString(request, "nodePath");
        if (StringUtil.isNotEmpty(nodePath)) {
            queryFilter.addFilter("nodePath", nodePath + "%");
        }
        queryFilter.addFilter("assignee", ContextUtil.getCurrentUserId());

        try {
            List<ProcessRun> processRunList = processRunService.queryCompletedMattersList(queryFilter);

            for (ProcessRun processRun : processRunList) {
                ActDefModel actDefModel = actDefModelService.getByProcDefId(processRun.getProcDefId());
                if (BeanUtils.isNotEmpty(actDefModel) && actDefModel.getIsPrintForm() == 1) {
                    processRun.setIsPrintForm(actDefModel.getIsPrintForm());
                }
            }
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("query.success", queryFilter.getPageBean().getTotalCount(), processRunList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("query.failure");

        }

    }

    /**
     * 我的请求页面跳转
     * @return 跳转路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/myRequestList")
    @Action(ownermodel=SysAuditModelType.PROCESS_CENTER,description ="查看我的请求页面")
    public String viewMyRequestList() {
        return "processRun/myRequestList";
    }

    /**
     * 流程实例下操作日志跳转
     * @param runId 实例id
     * @param model 视图模型对象
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX +"/form")
    @Action(description ="查看流程操作日志页面")
    public String viewProcessLogList(String runId,Model model) {
        model.addAttribute("runId",runId);
        return "workflow/processRun/list";
    }


    /**
     * 获取我的待办、我的办结流程分类
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/getMyRequestAndMyCompletedType")
    @ResponseBody
    public ResultData getMyRequestAndMyCompletedType(HttpServletRequest request){
        String category = RequestUtil.getString(request,"category");
        String userId =  ContextUtil.getCurrentUserId();
        List<GlobalType> processRunList = processRunService.queryMyRequestAndMyCompletedTypeList(userId,category);
        return getResultDataSuccess("query.success",processRunList);
    }

    /**
     * 我的请求列表
     *
     * @param request request
     * @return Object
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST + "/myRequestList")
    @Action(ownermodel=SysAuditModelType.PROCESS_CENTER,description = "查看我的请求列表数据", detail = "查看我的请求列表数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public Object myRequestList(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request);

        // 初始化请求参数
        String nodePath = RequestUtil.getString(request, "nodePath");

        if (StringUtil.isNotEmpty(nodePath)) {
            queryFilter.addFilter("nodePath", nodePath + "%");
        }
        queryFilter.addFilter("creatorId", ContextUtil.getCurrentUserId());

        try {
            List<ProcessRun> processRunList = processRunService.queryMyRequestList(queryFilter);
            if (processRunList != null) {
                for (ProcessRun process : processRunList) {
                    ProcessRun processRun = processRunService.getById(process.getRunId());
                    boolean isFirst = isFirst(processRun);
                    process.setCurrentNodeIsFirst(isFirst);
                }
            }
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("query.success", queryFilter.getPageBean().getTotalCount(), processRunList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 我的办结跳转路径
     * @return 跳转路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/myCompletedList")
    @Action(ownermodel=SysAuditModelType.PROCESS_CENTER,description = "查看我的办结页面",detail="查看我的办结页面")
    public String viewMyCompletedList() {
        return "processRun/myCompletedList";
    }

    /**
     * 我的办结
     * @param request request
     * @return Object
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST + "/myCompletedList")
    @Action(ownermodel=SysAuditModelType.PROCESS_CENTER,description = "查询我的办结列表数据", detail = "查询我的办结列表数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public Object myCompletedList(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request);
        String nodePath = RequestUtil.getString(request, "nodePath");

        if (StringUtil.isNotEmpty(nodePath)) {
            queryFilter.addFilter("nodePath", nodePath + "%");
        }
        queryFilter.addFilter("creatorId", ContextUtil.getCurrentUserId());

        try {
            List<ProcessRun> processRunList = processRunService.queryMyCompletedList(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("query.success", queryFilter.getPageBean().getTotalCount(), processRunList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 返回流程的详细信息
     * @param request request
     * @param model 视图模型
     * @return 页面路径
     * @throws Exception 异常
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/info")
    @Action(ownermodel=SysAuditModelType.PROCESS_CENTER,description = "查看流程明细信息")
    public String info(HttpServletRequest request, Model model) throws Exception {
        String curUserId = ContextUtil.getCurrentUserId();
        String runId = request.getParameter("runId");
        String prePage = RequestUtil.getString(request, "prePage");
        String preUrl = RequestUtil.getPrePage(request);
        String ctxPath = request.getContextPath();
        ProcessRun processRun = processRunService.getById(runId);
        String form = processRunService.getFormDetailByRunId(runId, ctxPath) + "&needHeadAndBottom=no";
        boolean isExtForm = false;
        if ("".equals(processRun.getFormDefId()) && StringUtil.isNotEmpty(processRun.getBusinessUrl())) {
            isExtForm = true;
        }

        ActDefModel actDefModel = actDefModelService.getOneById(processRun.getModelId());
        // 是否是第一个节点
        boolean isFirst = this.isFirst(processRun);
        // 是否允许办结转发
        boolean isFinishedDiver = this.isFinishedDiver(actDefModel, processRun);

        // 是否允许追回到发起人
        boolean isCanRecover = this.isCanRecover(processRun, isFirst, curUserId);
        // 是否允许追回
        boolean isCanRedo = this.isCanRedo(processRun, isFirst, curUserId);
        boolean isCopy = this.isCopy(actDefModel);
        // 是否允许打印
        boolean isPrintForm = this.isPrintForm(processRun, actDefModel);

        // 是否有全局流水号
        boolean hasGlobalFlowNo = PropertyUtil.getBooleanByAlias(SysProperty.GLOBAL_FLOW_NO);

        // 流程结束后的打印模板
        List<PrintTemplate> printTemplateList = bpmPrintTemplateService.getAllByFormKeyAndFlowFinish(processRun.getFormDefId());


        model.addAttribute("prePage", prePage).addAttribute("actDefModel", actDefModel)
                .addAttribute("processRun", processRun)
                .addAttribute("form", form)
                .addAttribute("isPrintForm", isPrintForm)
                .addAttribute("isExtForm", isExtForm).addAttribute("isFirst", isFirst)
                .addAttribute("isCanRecover", isCanRecover)
                .addAttribute("isCanRedo", isCanRedo)
                .addAttribute("isFinishedDiver", isFinishedDiver)
                .addAttribute("isCopy", isCopy)
                .addAttribute(RequestUtil.RETURNURL, preUrl)
                .addAttribute("hasGlobalFlowNo", hasGlobalFlowNo)
                .addAttribute("printTemplateList", printTemplateList);
        return "processRun/info";
    }

    private boolean isCopy(ActDefModel actDefModel) {
        Short status = actDefModel.getStatus();
        if (ActDefModel.STATUS_DISABLED.equals(status)) {
            return false;
        }
        if (ActDefModel.STATUS_INST_DISABLED.equals(status)) {
            return false;
        }
        return true;
    }


    /**
     * 取得流程实例扩展明细
     * @param request request
     * @param model 视图模型对象
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_GET)
    @Action(description = "查看流程实例明细页面", detail = "查看流程实例明细页面")
    public String viewGet(HttpServletRequest request, Model model){
        String runId = RequestUtil.getString(request, "runId");
        String procInstId = RequestUtil.getString(request,"procInstId");
        //用于判断抄送人tab是否显示
        ProcessRun processRun = processRunService.getByProcInstanceId(procInstId);
        model.addAttribute("runId", runId).addAttribute("procInstId",procInstId).addAttribute("processRun",processRun);
        return getAutoView();
    }


    /**
     * 查看流程运行明细
     * @param request request
     * @param model 视图模型对象
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/detail")
    @Action(description = "查看流程运行明细", detail = "查看流程运行明细")
    public String viewDetail(HttpServletRequest request, Model model){
        String runId = RequestUtil.getString(request, "runId");
        model.addAttribute("runId", runId);
        return "processRun/detail";
    }

    /**
     * 取得流程实例扩展明细
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/detail")
    @Action(description = "查询流程实例运行明细数据",detail = "查询流程实例运行明细数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData detail(HttpServletRequest request){
        ProcessRun processRun;
        String runId = RequestUtil.getString(request, "runId");
        String taskId = RequestUtil.getString(request, "taskId");
        try {
            if (!"".equals(runId)) {
                processRun = processRunService.getById(runId);
            } else {
                TaskEntity task = bpmService.getTask(taskId);
                processRun = processRunService.getByProcInstanceId(task.getProcessInstanceId());
            }
            if (processRun == null) {
                throw new Exception("实例不存在");
            }
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("query.success", processRun);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataSuccess("query.failure");
        }
    }

    /**
     * 流程实例流程变量页面
     * @param request request
     * @param model model
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/flowVarsAndValue")
    @Action(description = "查看流程实例流程变量页面")
    public String viewFlowVarsAndValue(HttpServletRequest request, Model model) {
        String runId = RequestUtil.getString(request, "runId");
        model.addAttribute("runId", runId);
        return getAutoView();
    }

    /**
     * 流程变量数据
     * @param request request
     * @param model 视图模型对象
     * @return ResultData
     */
    @RequestMapping("/flowVarsAndValue")
    @Action(description = "流程变量页面列表数据查询")
    @ResponseBody
    public ResultData getFlowVars(HttpServletRequest request, Model model) {
        String runId = RequestUtil.getString(request, "runId");
        String taskId = RequestUtil.getString(request, "taskId");
        String preUrl = RequestUtil.getPrePage(request);
        ProcessRun processRun;
        try {
            if (StringUtil.isNotEmpty(runId)) {
                processRun = processRunService.getById(runId);
            } else {
                TaskEntity task = bpmService.getTask(taskId);
                processRun = processRunService.getByProcInstanceId(task.getProcessInstanceId());
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            return getResultDataError("query.failure");
        }

         //1、获取流程实例中对应的表单和表，再根据程实例对应的自定义表名和businessKey查询出自定义表中流程变量的值
         //2、根据流程实例中对应的自定义表名查询流程定义中对应的自定义流程变量
        String defId = processRun.getProcDefId();

        //流程中instanceID等于executionId所以这儿的变量名为executionId
        String executionId = processRun.getProcInstId();

        //添加变量taskVarsList
        List<TaskVars> taskVarsList = null;
        if (StringUtil.isNotEmpty(defId)) {
            taskVarsList = taskVarsService.get_RU_TaskVarsByExecutionId(executionId);
            if (taskVarsList.size() == 0) {
                taskVarsList = taskVarsService.get_HI_TaskVarsByExecutionId(executionId);
            }
        }
        String businessKey = processRun.getBusinessKey();
        model.addAttribute("isReturn", request.getParameter("isReturn"))
                .addAttribute("businessKey", businessKey)
                .addAttribute("returnUrl", preUrl);

        return getResultDataSuccess("query.success", taskVarsList);
    }

    /**
     * 我的流程草稿
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/myDraft")
    @Action(ownermodel=SysAuditModelType.PROCESS_CENTER,description = "查看我的草稿页面",detail="查看我的草稿页面")
    public String viewMyDraft() {
        return getAutoView();
    }

    /**
     * 我的流程草稿列表
     * @param request request
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST + "/myDraft")
    @Action(ownermodel=SysAuditModelType.PROCESS_CENTER,description = "查询我的草稿列表数据", detail = "查询我的草稿列表数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData myDraftList(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        String userId = ContextUtil.getCurrentUserId();
        if (StringUtil.isEmpty(userId)) {
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("query.failure");
        }
        queryFilter.addFilter("userId", userId);
        try {
            List<ProcessRun> list = processRunService.queryMyDraft(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("query.success", queryFilter.getPageBean().getTotalCount(), list);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("query.failure");
        }

    }

    /**
     * 删除流程草稿同时删除业务数据
     * @param runId 运行id
     * @return ResultData
     */
    @ResponseStatus(value = HttpStatus.OK)
    @RequestMapping(value = "/delDraft", method = RequestMethod.DELETE)
    @Action(description = "删除草稿",detail = "删除草稿<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData delDraft(@RequestParam  String runId) {
        try{
            if (runId.contains(StringPool.COMMA)) {
                String[] runIdAry = runId.split(StringPool.COMMA);
                processRunService.delDraft(runIdAry);
            } else {
                processRunService.delDraft(runId);
            }
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("delete.success");
        }catch (Exception e){
            logger.error(e.getMessage());
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataSuccess("delete.failure");
        }
    }

    /**
     * 检查表单是否发生变化
     * @param request request
     * @return boolean
     */
    @RequestMapping("/checkForm")
    @ResponseBody
    public boolean checkForm(HttpServletRequest request) {
        String runId = RequestUtil.getString(request, "runId");
        ProcessRun processRun = processRunService.getById(runId);
        String formDefId = null;
        if (processRun != null) {
            formDefId = processRun.getFormDefId();
        }
        if (StringPool.ZERO.equals(formDefId)) {
            return false;
        }
        FormDef bpmFormDef = bpmFormDefService.getOneById(formDefId);
        FormDef defaultFormDef = bpmFormDefService.getDefaultPublishedByFormKey(bpmFormDef.getFormKey());
        if (defaultFormDef.getFormDefId().equals(formDefId)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 复制草稿
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/copyDraft")
    @Action(description = "复制草稿",detail = "复制草稿<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData copyDraft(HttpServletRequest request) {
        String runId = RequestUtil.getString(request, "runId");
        try {
            processRunService.copyDraft(runId);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("copyDraft.success");
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("copyDraft.failure");
        }
    }

    /**
     * 是否是第一个节点
     * @param processRun 流程实例
     * @return boolean
     * @throws Exception 异常
     */
    private boolean isFirst(ProcessRun processRun) throws Exception {
        boolean isFirst = false;
        if (BeanUtils.isEmpty(processRun)) {
            return isFirst;
        }
        String procInstId = processRun.getProcInstId();
        String procDefId = processRun.getProcDefId();
        List<TaskOpinion> taskOpinionList = taskOpinionService.getCheckOpinionByInstId(procInstId);
        String nodeId;

        // 判断起始节点后是否有多个节点
        if (NodeCache.isMultipleFirstNode(procDefId)) {
            nodeId = processRun.getStartNode();
        } else {
            FlowNodeInfo flowNodeInfo = NodeCache.getFirstNodeInfo(procDefId);

            if (flowNodeInfo == null) {
                return isFirst;
            }

            nodeId = flowNodeInfo.getNodeId();
        }
        for (TaskOpinion taskOpinion : taskOpinionList) {
            isFirst = nodeId.equals(taskOpinion.getTaskKey());
            if (isFirst) {
                break;
            }
        }
        return isFirst;
    }

    /**
     * 是否允许办结转办
     * @param actDefModel 流程模型
     * @param processRun 流程实例
     * @return boolean
     */
    private boolean isFinishedDiver(ActDefModel actDefModel, ProcessRun processRun) {
        if (ActDefModel.STATUS_INST_DISABLED.equals(actDefModel.getStatus())) {
            return false;
        }
        if (BeanUtils.isNotEmpty(actDefModel.getAllowFinishedDivert())) {
            return actDefModel.getAllowFinishedDivert().shortValue() == ActDefModel.ALLOW.shortValue() && processRun.getStatus().shortValue() == ProcessRun.STATUS_FINISH.shortValue();
        }
        return false;
    }

    /**
     * 是否能撤销
     *
     * <pre>
     *  	不是第一节点，是当前执行人并且是正在运行的流程 对应流程定义不能为禁用流程实例状态
     * </pre>
     *
     * @param processRun 流程实例
     * @param isFirst 是否是第一个节点
     * @param curUserId 当前用户id
     * @return boolean
     */
    private boolean isCanRecover(ProcessRun processRun, boolean isFirst, String curUserId) {
        String procDefId = processRun.getProcDefId();
        ActDefModel actDefModel = actDefModelService.getByProcDefId(procDefId);
        if (ActDefModel.STATUS_INST_DISABLED.equals(actDefModel.getStatus())) {
            return false;
        }
        return !isFirst && curUserId.equals(processRun.getCreatorId()) && processRun.getStatus().shortValue() != ProcessRun.STATUS_REDO;
    }

    /**
     * 是否可以追回
     *
     * <pre>
     * 是否可以追回，有以下几个判定条件：
     *  1、流程正在运行；
     *  2、流程非第一个节点；
     *  3、上一步执行人是当前用户；
     *  4、上一步操作是同意；
     *  5、目前该实例只有一个任务。
     *  6、 对应流程定义不能为禁用流程实例状态
     * </pre>
     *
     * @param processRun 流程实例
     * @param isFirst 是否是第一个节点
     * @param curUserId 当前用户id
     * @return boolean
     */
    private boolean isCanRedo(ProcessRun processRun, boolean isFirst, String curUserId) {
        if (!processRun.getStatus().equals(ProcessRun.STATUS_RUNNING) || isFirst) {
            return false;
        }
        String procDefId = processRun.getProcDefId();
        ActDefModel actDefModel = actDefModelService.getByProcDefId(procDefId);
        if (ActDefModel.STATUS_INST_DISABLED.equals(actDefModel.getStatus())) {
            return false;
        }
        String instanceId = processRun.getProcInstId();
        TaskOpinion taskOpinion = taskOpinionService.getLatestUserOpinion(instanceId, curUserId);
        if (taskOpinion == null) {
            return false;
        }

        Short checkStatus = taskOpinion.getCheckStatus();

        if (!TaskOpinion.STATUS_AGREE.equals(checkStatus)) {
            return false;
        }

        String taskKey = taskOpinion.getTaskKey();
        FlowNodeInfo flowNodeInfo = NodeCache.getNodeByActNodeId(processRun.getProcDefId(), taskKey);
        if (flowNodeInfo != null) {
            List<FlowNodeInfo> nextNodeInfo = flowNodeInfo.getNextFlowNodesInfo();
            List<String> nodeKeys = new ArrayList<>();
            for (FlowNodeInfo node : nextNodeInfo) {
                findUserNode(node, nodeKeys);
            }
            List<ProcessTask> tasks = bpmService.getTasks(instanceId);
            if (tasks.size() != 1) {
                return false;
            }

            if (nodeKeys.contains(tasks.get(0).getTaskDefinitionKey())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 递归找到用户节点
     * @param flowNodeInfo 当前节点
     * @param nodeKeys nodeKeys
     */
    private void findUserNode(FlowNodeInfo flowNodeInfo, List<String> nodeKeys) {
        if (flowNodeInfo.getNodeType().equals(FlowNodeInfo.TYPE_USERTASK)) {
            // 用户节点
            nodeKeys.add(flowNodeInfo.getNodeId());
        } else if (flowNodeInfo.getNodeType().equals(FlowNodeInfo.TYPE_EXCLUSIVEGATEWAY)) {
            List<FlowNodeInfo> nextNodes = flowNodeInfo.getNextFlowNodesInfo();
            for (FlowNodeInfo node : nextNodes) {
                findUserNode(node, nodeKeys);
            }
        }
    }

    /**
     * 是否允许打印表单
     *
     * <pre>
     * 	1.允许打印表单
     * 		是我的办结
     * 	2.允许
     * 		办结打印
     * 	3 允许
     * 		抄送打印
     *
     * </pre>
     *
     * @param processRun 流程实例
     * @param actDefModel 流程模型
     * @return boolean
     */
    private boolean isPrintForm(ProcessRun processRun, ActDefModel actDefModel) {
        if (actDefModel.getIsPrintForm() == null || actDefModel.getIsPrintForm().intValue() != 1 || processRun.getStatus().shortValue() != ProcessRun.STATUS_FINISH.shortValue()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 返回流程表单列表包括全局表单
     * @param request request
     * @param model 模型对象
     * @return 页面路径
     */
    @GetMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/getForm")
    @Action(description = "查看流程实例业务表单明细")
    public String viewGetForm(HttpServletRequest request, Model model){
        String runId = RequestUtil.getString(request, "runId");
        String ctxPath = request.getContextPath();
        String form = processRunService.getFormDetailByRunId(runId, ctxPath);
        ProcessRun processRun = processRunService.getById(runId);
        boolean isExtForm = false;
        if ("".equals(processRun.getFormDefId()) && StringUtil.isNotEmpty(processRun.getBusinessUrl())) {
            isExtForm = true;
        }

        model.addAttribute("processRun", processRun)
                .addAttribute("isFormEmpty", StringUtil.isEmpty(form))
                .addAttribute("isExtForm", isExtForm)
                .addAttribute("form", form);
        return getAutoView();
    }

    /**
     * 显示撤销对话框。
     * @param request request
     * @param model 模型对象
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/recoverDialog")
    @Action(description = "显示撤销对话框")
    public String recoverDialog(HttpServletRequest request, Model model) {
        String runId = RequestUtil.getString(request, "runId");
        int backToStart = RequestUtil.getInt(request, "backToStart");
        Map  handlersMap = ServiceUtil.getHandlerMap();
        model.addAttribute("backToStart", backToStart)
                .addAttribute("handlersMap",handlersMap)
                .addAttribute("runId", runId);
        return getAutoView();
    }

    /**
     * 是否允许撤销
     * @param request request
     * @throws Exception 异常
     */
    @RequestMapping("/checkRecover")
    @ResponseBody
    public ResultData checkRecover(HttpServletRequest request) throws Exception {
        String runId = RequestUtil.getString(request, "runId");
        // 是否允许撤销
        String msg = processRunService.checkRecover(runId);
        if(msg==null){
            return getResultDataSuccess("operation.success");
        }else{
            return getResultDataError(msg);
        }
    }

    /**
     * 显示追回对话框。
     * @param request request
     * @param model 模型对象
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/redoDialog")
    @Action(description = "显示追回对话框")
    public String redoDialog(HttpServletRequest request, Model model) {
        String runId = RequestUtil.getString(request, "runId");
        int backToStart = RequestUtil.getInt(request, "backToStart");
        Map  handlersMap = ServiceUtil.getHandlerMap();
        model.addAttribute("backToStart", backToStart)
                .addAttribute("handlersMap",handlersMap)
                .addAttribute("runId", runId);
        return "processRun/redoDialog";
    }

    /**
     * 是否允许追回
     * @param request request
     * @return ResultData
     * @throws Exception 异常
     */
    @RequestMapping("/checkRedo")
    @ResponseBody
    public ResultData checkRedo(HttpServletRequest request) throws Exception {
        String runId = RequestUtil.getString(request, "runId");
        return processRunService.checkRecoverByStart(runId);
    }

    /**
     * 任务追回,检查当前正在运行的任务是否允许进行追回。
     *
     * <pre>
     * 需要传入的参数：
     * runId:任务执行Id。
     * backToStart:追回到发起人。
     * memo:追回原因。
     *  任务能够被追回的条件：
     *  1.流程实例没有结束。
     *
     * 	任务追回包括两种情况。
     *  1.追回到发起人。
     *  4.如果这个流程实例有多个流程实例的情况，那么第一个跳转到驳回节点，其他的只完成当前任务，不进行跳转。
     *
     * </pre>
     *
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/recover")
    @Action(description = "任务追回",detail = "任务${operation}<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData recover(HttpServletRequest request){
        String runId = RequestUtil.getString(request, "runId");
        String informType = RequestUtil.getStringValues(request, "informType");
        String memo = RequestUtil.getString(request, "opinion");
        int backToStart = RequestUtil.getInt(request, "backToStart");
        String resultMsg;
        String operation;
        try {
            if (backToStart == 1) {
                // 撤销
                resultMsg = processRunService.recover(runId, informType, memo);
                operation="撤销";
            } else {
                // 追回
                resultMsg = processRunService.redo(runId, informType, memo);
                operation="追回";
            }
            if(resultMsg==null){
                SysAuditThreadLocalHolder.putParamerter("operation", operation);
                SysAuditThreadLocalHolder.putParamerter("fl", true);
                return getResultDataSuccess("operation.success");
            }else{
                SysAuditThreadLocalHolder.putParamerter("operation", operation);
                SysAuditThreadLocalHolder.putParamerter("fl", false);
                return getResultDataSuccess("operation.failure");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            String str = ExceptionUtil.getExceptionMessage(ex);
            if(StringUtil.isEmpty(str)) {
                return getResultDataError("operation.failure");
            }else {
                return getResultDataError("operation.failure", 1, str);
            }
        }
    }

    /**
     * 催促执行人、所属人（优先催促执行人，没有执行人就催促所属人）
     * @param request request
     * @param model 模型对象
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/urgeOwner")
    @Action(description = "打开催办窗口", detail = "打开催办窗口")
    public String urgeOwner(HttpServletRequest request, Model model){
        String procInstId = RequestUtil.getString(request, "procInstId");
        String inner = "";
        String mail = "";
        String shortmsg = "";
        ProcessRun processRun = processRunService.getByProcInstanceId(procInstId);
        String subject = null;
        if (processRun != null) {
            subject = processRun.getSubject();
        }
        SysTemplate temp = sysTemplateService.getDefaultByUseType(SysTemplate.USE_TYPE_URGE);
        if (BeanUtils.isNotEmpty(temp)) {
            inner = temp.getHtmlContent();
            mail = temp.getHtmlContent();
            shortmsg = temp.getPlainContent();
        }
        model.addAttribute("processSubject", subject).addAttribute("procInstId", procInstId)
                .addAttribute("inner", inner).addAttribute("mail", mail).
                addAttribute("shortmsg", shortmsg);
        return getAutoView();
    }

    /**
     * 执行催办动作
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/urgeSubmit")
    @Action(description = "执行催办", detail = "执行催办<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData urgeSubmit(HttpServletRequest request){
        try {
            String procInstId = RequestUtil.getString(request, "procInstId");
            String messgeType = RequestUtil.getStringAry(request, "messgeType");
            ProcessRun processRun = processRunService.getByProcInstanceId(procInstId);
            String parentProcDefId = processRunService.getParentProcessRunProcDefId(processRun);
            String subject = RequestUtil.getString(request, "subject");
            String processSubject = RequestUtil.getString(request, "processSubject");
            String opinion = RequestUtil.getString(request, "opinion");
            ActDefModel actDefModel = actDefModelService.getByProcDefId(processRun.getProcDefId());
            if (ActDefModel.STATUS_INST_DISABLED.equals(actDefModel.getStatus())) {
                return  getResultDataError( "run.urgeSubmit.error");
            }
            Boolean userProcessSubject = RequestUtil.getBoolean(request, "userProcessSubject");
            if (userProcessSubject || StringUtils.isEmpty(subject)) {
                subject = processSubject;
            }
            //消息模板
            Map<String, String> map = sysTemplateService.getTempByFun(SysTemplate.USE_TYPE_URGE);

            List<Task> taskList = taskService.createTaskQuery().processInstanceId(procInstId).list();
            taskMessageService.notify(taskList, messgeType, subject, map, opinion, parentProcDefId);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("run.urgeSubmit.success");
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("run.urgeSubmit.failure");
        }
    }

    /**
     * 流程图跳转页面  yaoluyang
     * @param request request
     * @param model 模型对象
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/bpmImg")
    @Action(description = "根据流程图查看审批情况")
    public String toBpmImg(HttpServletRequest request, Model model) {
        String procInstId = RequestUtil.getString(request, "procInstId");
        String runId = RequestUtil.getString(request, "runId");
        ProcessRun processRun ;
        if (StringUtils.isNotEmpty(runId)) {
            //bpm_pro_run
            processRun = processRunService.getById(runId);
            procInstId  = processRun.getProcInstId();
        }
        //获取流程实例
        else{
            processRun= processRunService.getByProcInstanceId(procInstId);
        }

        if(processRun==null){
            processRun= processRunService.getByProcInstanceIdFromHis(procInstId);
        }
        //将流程实例返回给页面
        model.addAttribute("procDefId", processRun.getProcDefId());
        model.addAttribute("subject", processRun.getSubject());
        //流程实例id返回给页面
        model.addAttribute("procInstId", procInstId);
        return "processRun/bpmImg";
    }

    /**
     * yly
     * 根据流程实例id 以及节点id获取流程节点信息
     * @param request request
     * @return TaskNodeStatus
     */
    @RequestMapping("/getFlowStatusByInstanceIdAndNodeId")
    @ResponseBody
    public TaskNodeStatus getFlowStatBpmServiceusByInstanceIdAndNodeId(HttpServletRequest request) {
        String instanceId = RequestUtil.getString(request, "instanceId");
        String taskKey = RequestUtil.getString(request, "nodeId");
        //获取流程任务审批状态//此处包含节点执行人的id 其他则应该为空 此处是获取节点的评价信息以及节点的执行人信息，
        // 如果节点评价信息为空，则查找节点的执行人信息
        TaskNodeStatus taskNodeStatus = bpmService.getNodeCheckStatusInfo(instanceId, taskKey);

        if (BeanUtils.isNotEmpty(taskNodeStatus.getTaskExecutorList())) {
            List<TaskExecutor> temExecutorList = taskNodeStatus.getTaskExecutorList();

            for (TaskExecutor taskExecutor : temExecutorList) {

                taskExecutor.setMainOrgName(getMainOrgName(taskExecutor.getExecuteId()));
            }
        }
        for (TaskOpinion taskOpinion : taskNodeStatus.getTaskOpinionList()) {
            //不是正在审批
            if (!TaskOpinion.STATUS_CHECKING.equals(taskOpinion.getCheckStatus())){
                continue;
            }
            String taskId = taskOpinion.getTaskId();
            //返回任务实体
            ProcessTask processTask = processRunService.getByTaskId(taskId);
            if(processTask!=null){
                //获取分配到任务的人员的id
                String assignee = processTask.getAssignee();
                if (ServiceUtil.isAssigneeNotEmpty(assignee)) {
                    //流程执行人的状态对象
                    TaskExeStatus taskExeStatus = new TaskExeStatus();
                    //获取用户姓名
                    String fullName = sysUserService.getOneById(assignee).getFullName();
                    taskExeStatus.setExecutor(fullName);
                    taskExeStatus.setExecutorId(assignee);
                    taskExeStatus.setMainOrgName(getMainOrgName(assignee));
                    boolean read = taskReadService.isRead(processTask.getId(), assignee);
                    taskExeStatus.setRead(read);

                    taskOpinion.setTaskExeStatus(taskExeStatus);


                } else {
                    //获取任务的候选人
                    Set<TaskExecutor> set = taskUserService.getCandidateExecutors(processTask.getId());
                    //备选流程执行人状态
                    List<TaskExeStatus> candidateUserStatusList = new ArrayList<>();

                    for (Iterator<TaskExecutor> it = set.iterator(); it.hasNext(); ) {
                        TaskExecutor t = it.next();
                        TaskExeStatus taskExeStatus = new TaskExeStatus();
                        taskExeStatus.setExecutorId(t.getExecuteId());
                        taskExeStatus.setMainOrgName(t.getMainOrgName());
                        taskExeStatus.setType(t.getType());
                        //被选任名字
                        taskExeStatus.setCandidateUser(t.getExecutor());
                        String executeId = t.getExecuteId();

                        if (TaskExecutor.USER_TYPE_USER.equals(t.getType())) {
                            //判断是否已读
                            boolean read = taskReadService.isRead(processTask.getId(), executeId);
                            taskExeStatus.setRead(read);

                        }
                        candidateUserStatusList.add(taskExeStatus);


                    }
                    taskOpinion.setCandidateUserStatusList(candidateUserStatusList);

                }
            }


        }
        return taskNodeStatus;
    }

    @RequestMapping("/getPrivacyLevelByRunId")
    @ResponseBody
    @Action(description = "根据运行id查看当前表单密级")
    public Integer getPrivacyLevelByRunId(@RequestParam String runId){
        try{
            return processRunService.getPrivacyLevelByRunId(runId);
        }catch (Exception e){
            e.printStackTrace();
            return 1;
        }
    }

    /**
     * 姚陆洋
     * 根据用户id获取组织名字
     * @param userId userId
     * @return 组织名称
     */

    private String getMainOrgName(String userId) {
        //根据用户id查询出用户所在的组织
        List<UserPosition> userPositions = userPositionService.queryByUserId(userId);
        String mainOrgName = "";
        for (UserPosition org : userPositions) {
            //判断是否是主要组织，是的话赋值，停止赋值
            if (org.getIsPrimary().equals(UserPosition.PRIMARY_YES)) {
                mainOrgName = org.getOrgName();
                break;
            }
        }
        return mainOrgName;

    }

}
